﻿using Blm.Utils.Utility;
using Newtonsoft.Json;
using System;
using System.Text.Json;
using System.Threading.Tasks;
using VisionCloud.Utility.Redis;

namespace VisionCloud.Utility
{
    /// <summary>
    /// 封装微信API服务
    /// </summary>
    public class WeChartApiHelper
    {
        /// <summary>
        /// 微信接口代理
        /// </summary>
        //private static readonly string wxApiAgent = "https://api.weixin.qq.com";
        private static readonly string wxApiAgent = "https://wx.saas.bzlrobot-ift.com";

        /// <summary>
        /// 小程序 appId
        /// </summary>
        private static readonly string appid = ConfigHelper.GetValue<string>("WxAppletInfo:AppId");

        /// <summary>
        /// 小程序 appSecret
        /// </summary>
        private static readonly string secret = ConfigHelper.GetValue<string>("WxAppletInfo:Secret");

        private static readonly string cacheTokenKey = $"Applet:{appid}:{secret}";

        /// <summary>
        /// 获取微信用户唯一标识OpenId
        /// </summary>
        /// <param name="jsCode">登录时获取的 code，可通过wx.login获取，是前端传到后端的</param>
        /// <returns></returns>
        public static async Task<string> GetWxOpenId(string jsCode)
        {
            var openid = string.Empty;
            var api = $"{wxApiAgent}/sns/jscode2session";
            var url = $"{api}?grant_type=authorization_code&appid={appid}&secret={secret}&js_code={jsCode}";

            using var res = await HttpUtility.GetAsync(url, timeout: 10);
            if (res != null && res.IsSuccessStatusCode)
            {
                using var content = await res.Content.ReadAsStreamAsync();
                using var jsonDocu = await JsonDocument.ParseAsync(content);
                if (jsonDocu.RootElement.TryGetProperty("openid", out JsonElement _openid))
                {
                    openid = _openid.GetString();
                }
            }
            return openid;
        }

        /// <summary>
        /// 获取微信接口调用凭据AccessToken
        /// </summary>
        /// <returns></returns>
        public static async Task<string> GetWxAccessToken()
        {
            var redisInstance = RedisHelper.Instance;
            var access_token = redisInstance.GetValue(cacheTokenKey);
            if (string.IsNullOrEmpty(access_token))
            {
                var api = $"{wxApiAgent}/cgi-bin/token";
                var url = $"{api}?grant_type=client_credential&appid={appid}&secret={secret}";
                using var res = await HttpUtility.GetAsync(url);
                if (res != null && res.IsSuccessStatusCode)
                {
                    using var content = await res.Content.ReadAsStreamAsync();
                    using var jsonDocu = await JsonDocument.ParseAsync(content);
                    var root = jsonDocu.RootElement;
                    if (root.TryGetProperty("access_token", out JsonElement _access_token))
                    {
                        access_token = _access_token.GetString();
                        var expires_in = root.GetProperty("expires_in").GetInt32();
                        await redisInstance.SetValueAsync(cacheTokenKey, access_token, TimeSpan.FromSeconds(expires_in));
                    }
                }
            }
            return access_token;
        }

        /// <summary>
        /// 文本内容安全识别:检查一段文本是否含有违法违规内容
        /// </summary>
        /// <returns></returns>
        public static async Task<(bool IsPass, string Reason)> WxMsgSecCheck(string content, string openid)
        {
            (bool IsPass, string Reason) Result = (false, string.Empty);
            var access_token = await GetWxAccessToken();
            var api = $"{wxApiAgent}/wxa/msg_sec_check?access_token={access_token}";
            var data = new { content, openid, version = 2, scene = 2 };

            using var res = await HttpUtility.PostAsync(api, JsonConvert.SerializeObject(data));
            if (res != null && res.IsSuccessStatusCode)
            {
                using var resContent = await res.Content.ReadAsStreamAsync();
                using var jsonDocu = await JsonDocument.ParseAsync(resContent);
                //Logger.Info($"【WxMsgSecCheck】：{api}--{JsonConvert.SerializeObject(data)}--{jsonDocu.RootElement}--【content:{content}】");
                if (jsonDocu.RootElement.TryGetProperty("result", out JsonElement check_result))
                {
                    var suggest = check_result.GetProperty("suggest").GetString();

                    var label = check_result.GetProperty("label").GetInt16();

                    if (suggest.Equals("pass", StringComparison.OrdinalIgnoreCase) && label == 100)
                        Result.IsPass = true;

                    Result.Reason = label switch
                    {
                        100 => "正常",
                        10001 => "广告",
                        20001 => "时政",
                        20002 => "色情",
                        20003 => "辱骂",
                        20006 => "违法犯罪",
                        20008 => "欺诈",
                        20012 => "低俗",
                        20013 => "版权",
                        21000 => "其他",
                        _ => "未知"
                    };
                }
                else
                {
                    Logger.Info($"【WxMsgSecCheck:ReseponseMsg】{jsonDocu.RootElement}");

                    //重新获取token
                    RedisHelper.Instance.DeleteKey(cacheTokenKey);
                    await GetWxAccessToken();
                }
            }
            return Result;
        }
    }
}